# vim: ts=4:sw=4:syntax=perl

# Take all the args and update portal ... and then
# redirect to page in the LP parameter.
use gri_secmgr qw(get_cookie_value redirect_header);
use gri_user_alert_config;

sub mm_form_delete_portal_process {
	my $portal_name=$::PARAM{portal_name};
	my $portal_dir=$::GRI_FRONTEND->get_global_directory("portals");
	my $delete_reports='off';
	if(exists($::PARAM{delreports})) {
		$delete_reports=$::PARAM{delreports};
	}
	my $portal_filename=hex_to_string($portal_name);
	my $x=$::GRI_FRONTEND->get_global_directory("portals");
	my $serror=undef;
	my $error=undef;
	if(! -f "$x/$portal_filename") {
		$serror="Error Removing Existing Portal";
		$error="Specified portal filename does not exist exist.";
	}
	my $cportal=new gri_portal_config("$x/$portal_filename");
	my $reports=$cportal->get_reports();
	if(@$reports && $delete_reports eq 'on') {
		my $reports_dir=$::GRI_FRONTEND->get_global_directory("reports");
		my $r=$::GRI_FRONTEND->get_portal_list(0,1);
		if($r && !defined($r->{error}) && $reports_dir) {
			for my $crep (@$reports) {
				my $keep=0;
				for my $cportal (@{$r->{repinfo}}) {
					if(grep {$_ eq $crep} @{$cportal->{reports}}) {
						$keep++; last if $keep>1;
					}
				}
				if($keep>1) {
					; 
				} else {
					unlink("$reports_dir/$crep.xml");
				}
			}
		}
	}

	if(!defined($error) && !unlink("$x/$portal_filename")) {
		$serror="Error Removing Existing Portal";
		$error="Unable to remove file $x/$portal_filename: $!";
	}
	if($error) {
		my $link=link_to_str("","","show_generic_error","?serror=".string_to_hex($serror).",error=".string_to_hex($error));
		if(!exists($::PARAM{lp})) {
			# We need to encode the current data for repopulation into the form!
			$link.=",previouspage=admin_page";
		}
		redirect_header(path => $link);
		exit;
	}

	my $link=link_to_str("","","/admin_page","");
	redirect_header(path => $link);
	exit;
}

